package sg.com.techstudio.nic.validator;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;

public abstract class BaseValidator {
	public static final String ERRORCODE_REQUIRED_FIELD = "required.field";
	protected static final Pattern EMAIL_PATTERN = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b", Pattern.CASE_INSENSITIVE);
	protected static final Pattern PHONE_PATTERN = Pattern.compile("[689]\\d{7}", Pattern.CASE_INSENSITIVE);
	protected static final Pattern POSTCODE_PATTERN = Pattern.compile("\\d{6}", Pattern.CASE_INSENSITIVE);
	
	protected boolean validateEmail(String email, String fieldName, boolean mandatory, MessageContext messages) {
		boolean hasError = false;
		if(!mandatory && StringUtils.isBlank(email))
			return hasError;
		if(StringUtils.isBlank(email)) {
			messages.addMessage(new MessageBuilder().error().source(fieldName)
					.code("required.field").build());
			hasError=true;
		} else if(!EMAIL_PATTERN.matcher(email).matches()) {
			messages.addMessage(new MessageBuilder().error().source(fieldName)
					.code("invalid.email").build());
			hasError=true;
		}
		return hasError;
	}
	
	protected boolean validateEmail(String email, String fieldName, MessageContext messages) {
		return validateEmail(email, fieldName, true, messages);
	}
	
	protected boolean validateEmptyString(String value, String fieldName, String errorCode, MessageContext messages) {
		if(StringUtils.isBlank(value)) {
			messages.addMessage(new MessageBuilder().error().source(fieldName)
					.code(errorCode).build());
			return false;
		}
		return true;
	}
	
	protected boolean validateEmptyString(String value, String fieldName, MessageContext messages) {
		return validateEmptyString(value, fieldName, ERRORCODE_REQUIRED_FIELD, messages);
	}
	
	protected void addMessage(String fieldName, String errorCode, MessageContext messages) {
		messages.addMessage(new MessageBuilder().error().source(fieldName)
				.code(errorCode).build());
	}
}
